package com.hx.vending.util;

import cn.jiguang.common.resp.APIConnectionException;
import cn.jiguang.common.resp.APIRequestException;
import cn.jpush.api.JPushClient;
import cn.jsms.api.SendSMSResult;
import cn.jsms.api.ValidSMSResult;
import cn.jsms.api.common.SMSClient;
import cn.jsms.api.common.model.SMSPayload;
import org.apache.log4j.Logger;

/**
 * Created by Administrator on 2018/12/5.
 */
public class JPushUtils {
    private static Logger LOG = Logger.getLogger(JPushUtils.class); // 获取logger实例

    //TODO 配置文件转移
    private static final String userAppkey = "eedfc9fa01f39d249edd3aa0";

    private static final String userMasterSecret = "6b28715f87fe516af23052ee";

    private static final SMSClient client = new SMSClient(userMasterSecret, userAppkey);

    /**
     * 发送短信验证码
     * phone :
     * 要发送验证码的手机号
     * return :
     * String msg_id;
     */
    public static String sendSMSCode(String phone){
        SMSPayload payload = SMSPayload.newBuilder().setMobileNumber(phone).setTempId(1).build();
        String result = null;
        try{
            SendSMSResult res = client.sendSMSCode(payload);

            LOG.info(res.toString());
            result = res.getMessageId();
        }catch (APIConnectionException e){
            LOG.error("Connection error. Should retry later. ", e);
        } catch (APIRequestException e) {
            LOG.info("HTTP Status: " + e.getStatus());

            LOG.info("Error Message: " + e.getMessage());

            LOG.error("Error response from JPush server. Should review and fix it. ", e);


        }
        return result;//返回的是"msg_id"对应的值
    }

    /**
     * 验证码校验
     * msg_id : 获取验证码时返回的参数结果
     * code  : 用户输入的验证码
     * return boolean;
     */
    public static Boolean sendValidSMSCode(String msgId, String code) {
        Boolean b = false;
        SMSClient client = new SMSClient(userMasterSecret, userAppkey);
        try{
            ValidSMSResult res = client.sendValidSMSCode(msgId, code);
            System.out.println(res.toString());
            //LOG.info(res.toString());
            b = res.getIsValid();
        }catch (APIConnectionException e){
            e.printStackTrace();
            System.out.println(e.getMessage());
            LOG.error("Connection error. Should retry later. ", e);
        }catch (APIRequestException e){
            e.printStackTrace();
            if (e.getErrorCode() == 50010) {
                // do something
            }
            System.out.println(e.getStatus() + " errorCode: " + e.getErrorCode() + " " + e.getErrorMessage());
            LOG.error("Error response from JPush server. Should review and fix it. ", e);
            LOG.info("HTTP Status: " + e.getStatus());
            LOG.info("Error Message: " + e.getMessage());
        }
        return b;
    }
}
